package com.marker.mo.amapsmoothmarker;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Button;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;

/**
 * 高德地图，仿滴滴车辆在地图上随机平滑移动Demo
 */
public class MainActivity extends AppCompatActivity {

    private MapView mMapView = null;
    private AMap aMap;
    private List<LatLng> startLatLngs;//静态车辆的数据
    private List<MySmoothMoveMarker> smoothMarkers;//平滑移动图标集合
    private int carNum = 6;// 生成车辆数目
    private LatLng centerLatLng = new LatLng(39.978419,116.249147);
    private Circle mCircle;
    public static final int STROKE_COLOR = Color.parseColor("#384D73B3");// 定位范围线条颜色
    public static final int FILL_COLOR = Color.parseColor("#384D73B3");// 定位范围的填充颜色
    private Button start, reset,reset100;
    private CircleOptions options;
    private List<BusBean.ListBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        initView();
        initData();
//        getUserData("https://wx.shenghuoquan.cn/WxBusServer/ApiData.do");
    }

    private void initView() {
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                centerLatLng, 16, 0, 0)));
        start = (Button) findViewById(R.id.put);
        reset = (Button) findViewById(R.id.run);
        reset100 = (Button) findViewById(R.id.run100);

        options = new CircleOptions();
        options.strokeWidth(1f);
        // 设置透明圆形图层
//        options.fillColor(Color.argb(0, 0, 0, 255));
//        options.strokeColor(Color.argb(0, 0, 0, 255));
        options.fillColor(STROKE_COLOR);
        options.strokeColor(FILL_COLOR);
        options.center(centerLatLng);
        options.radius(500);

        /**
         * 展示平滑移动车辆
         */
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carNum=6;
                aMap.clear();//清空地图覆盖物
                initData();
                mCircle = aMap.addCircle(options);
                if (smoothMarkers != null){
                    if (smoothMarkers.size() != 0){
                        for (int i = 0; i < smoothMarkers.size(); i++) {
                            smoothMarkers.get(i).destroy();
                        }
                    }
                }
                smoothMarkers = new ArrayList<MySmoothMoveMarker>();

                for (int i = 0; i < carNum; i++) {
                    List<LatLng> latLng = randomGenerateLatLngs(startLatLngs.get(i));
                    startMoveCar(latLng, i, true);
                }
            }
        });
        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aMap.clear();//清空地图覆盖物
                initData();
                if (smoothMarkers != null){
                    if (smoothMarkers.size() != 0){
                        for (int i = 0; i < smoothMarkers.size(); i++) {
                            smoothMarkers.get(i).destroy();
                        }
                    }
                }
                smoothMarkers = new ArrayList<MySmoothMoveMarker>();
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LogUtil.e("marker id"+marker.getId());
                return true;
            }
        });

    }

    private void initData() {
        // 随机生成中心点附近的行驶起点
        startLatLngs = new ArrayList<>();
        double lat = centerLatLng.latitude;
        double lng = centerLatLng.longitude;
        for (int i = 0; i < carNum; i++) {
            LatLng newLatLng = new LatLng(lat + (Math.random() > 0.5 ? 1 : -1) * (Math.random() * 3) / Math.pow(10, 3), lng + (Math.random() > 0.5 ? 1 : -1) * (Math.random() * 3) / Math.pow(10, 3));
            startLatLngs.add(newLatLng);
        }
        LogUtil.e(startLatLngs.size()+"");
    }


    /**
     *  开始平滑移动车辆
     *  @param latLngs 车辆轨迹坐标数组
     *  @param index 车辆序号
     *  @param isFirst 是否首次移动
     */

    public void startMoveCar(List<LatLng> latLngs, final int index, boolean isFirst) {
        Log.i("latLngs的大小", latLngs.size() + "");
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.drawable.car_up_white);
        // 获取轨迹坐标点
        List<LatLng> points = new ArrayList<>(latLngs);
        LogUtil.e("points "+points.size());
        MySmoothMoveMarker smoothMarker;
        if (isFirst) {
            smoothMarker = new MySmoothMoveMarker(aMap);
            smoothMarkers.add(smoothMarker);
        } else {
            smoothMarker = smoothMarkers.get(index);
        }
        // 设置滑动的图标
        smoothMarker.setDescriptor(descriptor);
        LatLng drivePoint = points.get(0);
        Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(points, drivePoint);
        points.set(pair.first, drivePoint);
        List<LatLng> subList = points.subList(pair.first, points.size());

        // 设置滑动的轨迹左边点
        smoothMarker.setPoints(subList);
        // 设置滑动的总时间
        smoothMarker.setTotalDuration(subList.size() * 4);
        smoothMarker.setMoveListener(new MySmoothMoveMarker.MoveListener() {
            @Override
            public void move(double v) {
            }

            @Override
            public void stop(LatLng latLng) {
                LogUtil.e("动画完成");
                ArrayList<LatLng> result = randomGenerateLatLngs(latLng);
                startMoveCar(result, index, false);
            }
        });
        // 开始滑动
        smoothMarker.startSmoothMove();
    }

    /**
     * 生成以中心点附近指定radius内的坐标数组
     *
     * @param startLatLng 起点坐标
     * @return
     */
    private ArrayList<LatLng> randomGenerateLatLngs(LatLng startLatLng) {
        ArrayList<LatLng> latLngs = new ArrayList<>();
        latLngs.add(startLatLng);
        double lat = centerLatLng.latitude;
        double lng = centerLatLng.longitude;
        for (int i = 0; i < 50; i++) {
            double newLat = lat + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            double newLng = lng + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            LatLng newLatLng = new LatLng(newLat, newLng);
            if (mCircle.contains(newLatLng)) {
                latLngs.add(newLatLng);
            }
        }
        // 如果随机生成的数组个数为0，则再随机添加一个距离中心点更近的坐标
        if (latLngs.size() == 1) {
            latLngs.add(new LatLng(lat + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3), lng + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3)));
        }
        return latLngs;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

}
